package com.godme.user.service.impl;

import com.godme.user.service.UserService;
import com.google.common.base.Objects;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;


@Component
public class UserServiceImpl implements UserService {

    private final String users = "users";


    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public boolean isRegistered(String username) {
        return redisTemplate.opsForHash().hasKey(users, username);
    }

    public void register(String username, String password) {
        redisTemplate.opsForHash().put(users, username, password);
    }

    public boolean auth(String username, String password) {
        HashOperations<String, Object, Object> operations = redisTemplate.opsForHash();
        if(operations.hasKey(users, username)){
            return Objects.equal(password, operations.get(users, username));
        }
        return false;
    }

    public String sign(String username, String password) {
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, username);
        return token;
    }

    public String check(String token) {
        return redisTemplate.opsForValue().get(token);
    }
}
